﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;

namespace SiteImageDownloader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void txttextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private int pageCount;
        private string url;
        private string reg = "<img src=\"(.*?\\.jpg)\" .*id=\"aeaoofnhgocdbnbeljkmbjdmhbcokfdb-mousedown\">";



        private void btnbutton1_Click(object sender, EventArgs e)
        {
            reg = txtReg.Text;
            pageCount = int.Parse(txtPageCount.Text);
            url = txtURL.Text;
            Reg = new Regex(reg);
            DownloadImages(url, reg, pageCount);

        }

        private Regex Reg;
        private async void DownloadImages(string url, string reg, int pageCount)
        {
            GeneratePages(url, pageCount);
            
            foreach (var page in WebPageList)
            {
                lbStatus.Text = page;
                try
                {
                    await DownloadImage(page, reg);
                }
                catch (Exception)
                {
                    
                   
                }
                
             
            }
            lbStatus.Text = "Done!";

        }
        WebClient wc = new WebClient();
        private async Task<string> DownloadImage(string page, string reg)
        {
            string result = await wc.DownloadStringTaskAsync(new Uri(page));
            var m = Reg.Match(result).ToString();
            if (!string.IsNullOrWhiteSpace(m))
            {
                var data = await wc.DownloadDataTaskAsync(m);
                try
                {
                    var path = m.Substring(m.LastIndexOf('/')+1);
                    File.WriteAllBytes("images\\"+path, data);
                }
                catch (Exception)
                { 
                  
                }
           
            }
            return "ok";
        }
        List<string> WebPageList = new List<string>();
        private void GeneratePages(string url, int pageCount)
        {
            WebPageList.Clear();

            WebPageList.Add(url);

            var index = url.IndexOf(".html");
            url=url.Insert(index, @"_{0}");
           
            for (int i = 2; i <= pageCount; i++)
            {
                WebPageList.Add(string.Format(url, i));
            }

        }
    }
}
